package com.dyh.quickdemozwei;

import com.alibaba.fastjson.JSON;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public interface SignUtils {

    static String sign(Map<String, Object> requestParams, String appKey, String appSecret){
//        requestParams.put("token",token);
        requestParams.put("app_key",appKey);
        //追加


        return sign(requestParams,appSecret);

    }

    static String sign(Map<String, Object> requestParams, String appSecret){
        String signSource = buildSignSource(requestParams,appSecret);
        return md5(signSource).toUpperCase();

    }

     static String buildSignSource(Map<String, Object> requestParams, String clientSecret) {
        if (null != requestParams && !requestParams.isEmpty()) {
            Map<String, Object> signSrcMap = requestParams;
            if (!(requestParams instanceof TreeMap)) {
                signSrcMap = new TreeMap();
                ((Map)signSrcMap).putAll(requestParams);
            }

            StringBuilder signSrcBuilder = (new StringBuilder()).append(clientSecret);//头添加
            Iterator it = ((Map)signSrcMap).entrySet().iterator();

            while(it.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry)it.next();
                signSrcBuilder.append((String)entry.getKey()).append(JSON.toJSONString(entry.getValue()));
            }

            signSrcBuilder.append(clientSecret);//尾添加
            return signSrcBuilder.toString();
        } else {
            return "";
        }
    }

     static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes("UTF-8"));
            byte[] result = md.digest();
            StringBuffer sb = new StringBuffer(32);

            for(int i = 0; i < result.length; ++i) {
                int val = result[i] & 255;
                if (val <= 15) {
                    sb.append("0");
                }

                sb.append(Integer.toHexString(val));
            }

            return sb.toString();
        } catch (Exception var6) {
            throw new AssertionError();
        }
    }
}
